//
//  cooperatingPartnerViewController.m
//  lmq
//
//  Created by 千翼网络科技 on 2017/4/3.
//  Copyright © 2017年 yuanxin. All rights reserved.
//

#import "cooperatingPartnerViewController.h"
#import "configddd.h"
#import <Masonry/Masonry.h>
#import "UIImageView+WebCache.h"
#import "cooperatingPartnerTableViewCell.h"
#import "cooperatingPartnerCollectionViewCell.h"
#import "goodsListViewController.h"

@interface cooperatingPartnerViewController ()

@end

@implementation cooperatingPartnerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(locationNotification:) name:@"location" object:nil];
    [self requestData];
    
    index = 0;
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake((scrWidth() - screenScale(120) - screenScale(100)) / 3 , screenScale(200));
    layout.minimumLineSpacing = screenScale(20);
    layout.minimumInteritemSpacing = screenScale(20);
    
    self.cooperatingPartnerTableView = [[UITableView alloc]init];
    self.waitLable = [[UILabel alloc]init];
    self.cooperatingPartnerCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(screenScale(120) + screenScale(20), screenScale(20), scrWidth() - screenScale(120) - screenScale(40), scrHeight() - 64 - 49 - screenScale(80)) collectionViewLayout:layout];
    
}

#pragma mark ---------------------------------- NSNotification

- (void)locationNotification:(NSNotification *)text{
    
    if ([text.userInfo[@"select"]isEqualToString:@"yes"]) {
        
        _location = text.userInfo[@"location"];
        [self goodsListRequestData:dataArray[0][@"id"]];
    }
}

#pragma mark ---------------------------------- requestData

- (void)requestData{
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication]keyWindow] animated:YES];
    hud.tag = 500;
    //提示文本
    hud.labelText = @"正在加载...";
    //是否有遮罩
    hud.dimBackground = YES;
    
    NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
    [productParams setValue: [PublicFunction getConfigWithKey:@"token"] forKey:@"token"];
    
    [[MNetworkHandler sharedInstance]conURL:Cooperation_Type
                                networkType:NetWorkPOST
                                     params:productParams
                                   delegate:nil
                                    showHUD:NO
                               successBlock:^(id returnData) {
                                   if ([[returnData objectForKey:@"code"]intValue]==1) {
                                       
                                       dataArray = [returnData objectForKey:@"data"];
                                       [_cooperatingPartnerTableView reloadData];
                                       
                                       [self goodsListRequestData:dataArray[0][@"id"]];
                                       
//                                       NSLog(@"==\n\n\n==dataArray====%@",dataArray);
                                       
                                       [hud removeFromSuperview];
                                   }
                                   else if ([[returnData objectForKey:@"code"]intValue]==-1){
                                       
                                       [hud removeFromSuperview];
                                       [PublicFunction showAlert:nil message:[returnData objectForKey:@"msg"] duration:5.0f];
                                       
                                   }else{
                                   
                                       [hud removeFromSuperview];
                                       [PublicFunction showAlert:nil message:[returnData objectForKey:@"msg"] duration:5.0f];
                                   }
                               } failureBlock:^(NSError *error) {
                                   
                                   [hud removeFromSuperview];
                                   NSLog(@"%@",error);
                                   [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
                               }];
}

- (void)goodsListRequestData:(NSString *)str{

    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication]keyWindow] animated:YES];
    hud.tag = 500;
    //提示文本
    hud.labelText = @"正在加载...";
    //是否有遮罩
    hud.dimBackground = YES;
    
    NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
    [productParams setValue: str forKey:@"type"];
//    [productParams setValue:[PublicFunction getConfigWithKey:@"token"] forKey:@"token"];
    [productParams setValue:_location forKey:@"city"];
//    [productParams setValue:@"沈阳" forKey:@"city"];
    
    
    NSLog(@"%@",productParams);
    
    [[MNetworkHandler sharedInstance]conURL:Cooperation_List
                                networkType:NetWorkPOST
                                     params:productParams
                                   delegate:nil
                                    showHUD:NO
                               successBlock:^(id returnData) {
                                   if ([[returnData objectForKey:@"code"]intValue]==1) {
                                       
                                       _waitLable.hidden = YES;
                                       _cooperatingPartnerCollectionView.hidden = NO;
                                       
                                       cooperationListDic = [returnData objectForKey:@"data"];
                                       [_cooperatingPartnerCollectionView reloadData];
                                       
//                                       NSLog(@"==\n\n\n==cooperationListDic====%@",cooperationListDic);
                                       
                                       [hud removeFromSuperview];
                                   }
                                   else if ([[returnData objectForKey:@"code"]intValue]==-1){
                                       
                                       [hud removeFromSuperview];
                                       [PublicFunction showAlert:nil message:[returnData objectForKey:@"msg"] duration:5.0f];
                                       
                                   }else{
                                   
                                       [hud removeFromSuperview];
                                       _waitLable.hidden = NO;
                                       _cooperatingPartnerCollectionView.hidden = YES;
                                       
                                   }
                               } failureBlock:^(NSError *error) {
                                   
                                   [hud removeFromSuperview];
                                   NSLog(@"%@",error);
                                   [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
                               }];
}

#pragma mark ------------------------------- init

- (void)setCooperatingPartnerTableView:(UITableView *)cooperatingPartnerTableView{

    _cooperatingPartnerTableView = cooperatingPartnerTableView;
    _cooperatingPartnerTableView.delegate = self;
    _cooperatingPartnerTableView.dataSource = self;
    _cooperatingPartnerTableView.backgroundColor = getColor(@"f4f4f4");
    _cooperatingPartnerTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_cooperatingPartnerTableView];
    [_cooperatingPartnerTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).with.offset(0);
        make.left.mas_equalTo(self.view).with.offset(0);
        make.bottom.mas_equalTo(self.view).with.offset(0);
        
        make.width.mas_equalTo(screenScale(120));
    }];
}

- (void)setCooperatingPartnerCollectionView:(UICollectionView *)cooperatingPartnerCollectionView{

    _cooperatingPartnerCollectionView = cooperatingPartnerCollectionView;
    _cooperatingPartnerCollectionView.delegate = self;
    _cooperatingPartnerCollectionView.dataSource = self;
    _cooperatingPartnerCollectionView.backgroundColor = getColor(@"ffffff");
    [_cooperatingPartnerCollectionView registerClass:[cooperatingPartnerCollectionViewCell class] forCellWithReuseIdentifier:@"identifier"];
    [_cooperatingPartnerCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionViewHeader"];
    [self.view addSubview:_cooperatingPartnerCollectionView];
    [_cooperatingPartnerTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).with.offset(screenScale(20));
        make.left.mas_equalTo(self.view).with.offset(screenScale(120));
        make.bottom.mas_equalTo(self.view).with.offset(0);
        
        make.width.mas_equalTo(scrWidth() - screenScale(120));
    }];
}

- (void)setWaitLable:(UILabel *)waitLable{

    _waitLable = waitLable;
    _waitLable.frame = CGRectMake(screenScale(120) + screenScale(20), 0, scrWidth() - screenScale(120) - screenScale(40), scrHeight() - 64 - 49 - screenScale(100));
    _waitLable.text = @"----  敬请期待  ----";
    _waitLable.textColor = getColor(@"c8c8c8");
    _waitLable.font = get4sFont(15);
    _waitLable.textAlignment = NSTextAlignmentCenter;
    _waitLable.hidden = YES;
    [self.view addSubview:_waitLable];
}

#pragma mark ------------------------------- SDCycleScrollViewDelegate
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    NSLog(@"---点击了第%ld张图片", (long)index);
    
    goodsListViewController *goodsVC = [[goodsListViewController alloc]init];
//    goodsVC.title = cooperationListDic[@"list"][index][@"name"];
    goodsVC.partnerId = cooperationListDic[@"banner"][index][@"pid"];
    goodsVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:goodsVC animated:YES];
}

#pragma mark ------------------------------- UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    [self goodsListRequestData:dataArray[indexPath.row][@"id"]];
    index = indexPath.row;
    [_cooperatingPartnerTableView reloadData];
}

#pragma mark ------------------------------- UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    [tableView registerClass:[cooperatingPartnerTableViewCell class] forCellReuseIdentifier:@"identifier"];
    cooperatingPartnerTableViewCell *cell = (cooperatingPartnerTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"identifier" forIndexPath:indexPath];
    
    cell.tittleLable.text = dataArray[indexPath.row][@"name"];
    if (indexPath.row == index) {
        
        cell.tittleLable.textColor = getColor(@"2b2b2b");
        cell.backgroundColor = getColor(@"ffffff");
    }else{
    
        cell.tittleLable.textColor = getColor(@"c8c8c8");
        cell.backgroundColor = getColor(@"f4f4f4");
    }
    
    return cell;
}

#pragma mark ------------------------------- UICollectionViewDelegate

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    UICollectionReusableView *reusableView = nil;
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        
        UICollectionReusableView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionViewHeader" forIndexPath:indexPath];
        
        for (UIView *view in headView.subviews) {
            
            [view removeFromSuperview];
        }
        
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, scrWidth() - screenScale(120) - screenScale(40), screenScale(185) + screenScale(70))];
        [headView addSubview:view];
        
        NSMutableArray *picArray = [[NSMutableArray alloc]init];
        for (int i = 0 ; i < [cooperationListDic[@"banner"] count] ; i ++) {
            
            NSString *str = cooperationListDic[@"banner"][i][@"pic"];
            NSString *urlN = manage(AP_HOST, str);
            NSString *strUrl = [urlN stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];
            [picArray addObject:strUrl];
        }
        
        [self.cycleScrollView setLocalizationImageNamesGroup:picArray];
        
        self.cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, scrWidth() - screenScale(120) - screenScale(40), screenScale(185)) imageNamesGroup:picArray];
        self.cycleScrollView.backgroundColor = [UIColor whiteColor];
        self.cycleScrollView.autoScroll = YES;
        self.cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
        self.cycleScrollView.delegate = self;
        self.cycleScrollView.pageDotColor = [UIColor grayColor]; // 自定义分页控件小圆标颜色
        self.cycleScrollView.currentPageDotImage = [UIImage imageNamed:@"hei"];
        self.cycleScrollView.pageDotImage = [UIImage imageNamed:@"hui"];
        self.cycleScrollView.placeholderImage = [UIImage imageNamed:@""];
        [view addSubview:self.cycleScrollView];
        
        UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(0, screenScale(185), scrWidth() - screenScale(120) - screenScale(40), screenScale(70))];
        lable.text = @"----  店铺  ----";
        lable.font = get4sFont(15);
        lable.textColor = getColor(@"c8c8c8");
        lable.textAlignment = NSTextAlignmentCenter;
        [view addSubview:lable];
        
        reusableView = headView;
    }
    return reusableView;
}
// headView 大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    CGSize size={scrWidth() - screenScale(120) - screenScale(40),screenScale(185) + screenScale(70)};
    return size;
}

-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    return YES;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    goodsListViewController *goodsVC = [[goodsListViewController alloc]init];
    goodsVC.title = cooperationListDic[@"list"][indexPath.row][@"name"];
    goodsVC.partnerId = cooperationListDic[@"list"][indexPath.row][@"id"];
    goodsVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:goodsVC animated:YES];
}

#pragma mark ------------------------------- UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return [cooperationListDic[@"list"] count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identify = @"identifier";
    cooperatingPartnerCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
    
    NSDictionary *dict = cooperationListDic[@"list"][indexPath.row];
    NSString *urlGood = [dict objectForKey:@"logo"];
    NSString *urlN = manage(AP_HOST, urlGood);
    NSString *strUrl = [urlN stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];
    NSURL *urlW = [NSURL URLWithString:strUrl];
    [cell.imageshow sd_setImageWithURL:urlW placeholderImage:[UIImage imageNamed:@"niunai"]];
    
    cell.myLabel.text = cooperationListDic[@"list"][indexPath.row][@"name"];
    
    return cell;
}







@end
